import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:sui_shou_pai/chat/entity/chat_record.dart';
import 'package:sui_shou_pai/chat/entity/global.dart';
import 'package:sui_shou_pai/chat/entity/message_model.dart';
import 'package:sui_shou_pai/chat/init/init_map.dart';
import 'package:sui_shou_pai/chat/init/interface.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';
import 'package:sui_shou_pai/record/record_detail.dart';
import 'package:sui_shou_pai/utils/storage_util.dart';

class ChatRecordsList extends StatefulWidget {
  final String id;

  final String avatar;

  const ChatRecordsList({Key key, @required this.id, this.avatar})
      : super(key: key);

  @override
  ChatRecordsListState createState() {
    return ChatRecordsListState();
  }
}

class ChatRecordsListState extends State<ChatRecordsList> {
  List<ChatRecord> records = [];

  JPush jPush = InitMap.jPush;

  String debugLabel = "";

  /**
   * 极光推送
   */
  Future<void> initPlatFormState() async {
    String platform = "";

    try {
      jPush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        String content = message["alert"];
        var json = jsonDecode(message["extras"]["cn.jpush.android.EXTRA"]);
        setState(() {
          if (json["id"] == widget.id) {
            ChatRecord record = new ChatRecord("0", widget.id.toString(),
                Global.me, content, Global.currentTimeMillis(), "0");
            records.insert(0, record);
            updateMessage(records);
          }
        });
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("通过点击推送进入app：$message");
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("接收到自定义消息：$message");
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        print("通知权限发生变更：$message");
      });
    } on PlatformException {
      platform = "平台版本获取失败";
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    records = InitMap.recordsMap[widget.id];
    initPlatFormState();
  }

  /**
   * 点击发送，增加一条信息
   */
  void click(ChatRecord record) {
    setState(() {
      if (widget.id != Global.me) {
        records.insert(0, record);
        updateMessage(records);
      }
    });
  }

  void updateMessage(List<ChatRecord> records) {
    if (records.length != 0) {
      MessageModel messageModel = InitMap.messageMap[widget.id];
      messageModel.setTime(records.first.time.substring(0, 10));
      messageModel.setContent(records.first.content);
      InitMap.messageMap.update(widget.id, (value) => messageModel);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.id != "9") {
      if (records != null && records.length != 0) {
        return ListView.builder(
          reverse: true,
          shrinkWrap: true,
          itemCount: records.length,
          itemBuilder: (context, index) {
            if (records[index].sender == Global.me) {
              return buildRightItem(records[index]);
            }
            return buildLeftItem(records[index]);
          },
        );
      } else {
        return Container(
          alignment: Alignment.topCenter,
          width: MediaQuery.of(context).size.width,
          margin: EdgeInsets.only(top: 30.0),
          child: Text("暂无记录"),
        );
      }
    } else {
      return buildSystemItem(records);
    }
  }

  /**
   * 对方
   */
  Widget buildLeftItem(ChatRecord record) {
    return Container(
        margin: EdgeInsets.fromLTRB(0, 15, 0, 0),
        child: ListTile(
            leading: Container(
              decoration: BoxDecoration(
                borderRadius: borderRadiusAll40(),
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(widget.avatar),
                ),
              ),
              width: 48.0,
              height: 48.0,
            ),
            title: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width - 120,
                  ),
                  decoration: new BoxDecoration(
                      borderRadius: borderRadiusAll8(), color: Colors.white),
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                  child: Text(
                    record.content,
                    style: TextStyle(fontSize: 18.0),
                  ),
                )
              ],
            )));
  }

  /**
   * 自己
   */
  Widget buildRightItem(ChatRecord record) {
    return Container(
        margin: EdgeInsets.fromLTRB(0, 15, 0, 0),
        child: ListTile(
            trailing: Container(
              decoration: BoxDecoration(
                borderRadius: borderRadiusAll40(),
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(InitInformation.avatar),
                ),
              ),
              width: 48.0,
              height: 48.0,
            ),
            title: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width - 120,
                  ),
                  decoration: new BoxDecoration(
                      borderRadius: borderRadiusAll8(),
                      color: Color.fromARGB(255, 76, 139, 255)),
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                  child: Text(
                    record.content,
                    style: TextStyle(fontSize: 18.0, color: Colors.white),
                  ),
                )
              ],
            )));
  }

  /**
   * 系统
   */
  Widget buildSystemItem(List<ChatRecord> records) {
    if (records.length != 0) {
      return ListView.builder(
        reverse: true,
        shrinkWrap: true,
        itemCount: records.length,
        itemBuilder: (context, index) {
          return Container(
              margin: EdgeInsets.fromLTRB(0, 15, 0, 0),
              child: ListTile(
                  leading: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        fit: BoxFit.cover,
                        image: NetworkImage(widget.avatar),
                      ),
                    ),
                    width: 40.0,
                    height: 40.0,
                  ),
                  title: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Container(
                          constraints: BoxConstraints(
                            maxWidth: MediaQuery.of(context).size.width - 120,
                          ),
                          decoration: new BoxDecoration(
                              borderRadius: borderRadiusAll8(),
                              color: Colors.white),
                          padding: EdgeInsets.symmetric(
                              vertical: 10, horizontal: 16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                getRealContent(records[index].content),
                                style: TextStyle(fontSize: 18.0),
                              ),
                              SizedBox(
                                height: 10.0,
                              ),
                              InkWell(
                                child: Container(
                                  height: 40,
                                  decoration: new BoxDecoration(
                                      borderRadius: borderRadiusAll4(),
                                      color: getBackColor(records[index])),
                                  child: Center(
                                    child: Text(
                                      getTitle(records[index]),
                                      style: TextStyle(
                                          fontSize: 16.0,
                                          fontWeight: FontWeight.bold,
                                          color: getTextColor(records[index])),
                                    ),
                                  ),
                                ),
                                onTap: () async {
                                  setState(() {
                                    if (records[index].isRead == "0") {
                                      records[index].setIsRead();
                                      ChatInterface.changeSystemIsRead(
                                          records[index].id);
                                    } else {
                                      print("已经是已读状态");
                                    }
                                    delayed(getRealId(records[index].content));
                                  });
                                },
                              ),
                            ],
                          ))
                    ],
                  )));
        },
      );
    } else {
      return Container(
        alignment: Alignment.topCenter,
        width: MediaQuery.of(context).size.width,
        margin: EdgeInsets.only(top: 30.0),
        child: Text("暂无记录"),
      );
    }
  }

  String getTitle(ChatRecord record) {
    if (record.isRead == "0") {
      return "收到";
    } else {
      return "查看详情";
    }
  }

  Color getBackColor(ChatRecord record) {
    if (record.isRead == "0") {
      return Colors.blue;
    } else {
      return greyF3F3F3;
    }
  }

  Color getTextColor(ChatRecord record) {
    if (record.isRead == "0") {
      return Colors.white;
    } else {
      return Colors.grey;
    }
  }

  String getRealContent(String content) {
    int index = 0;
    for (int i = 0; i < content.length; i++) {
      if (content[i] == '#') {
        index = i;
      }
    }
    return content.substring(index + 1, content.length);
  }

  String getRealId(String content) {
    int index = 0;
    for (int i = 0; i < content.length; i++) {
      if (content[i] == '#') {
        index = i;
      }
    }
    return content.substring(0, index);
  }

  // 根据id修改记录实体状态
  Future<void> acceptPhotoRecord(String id) async{
    print("---------------id------" + id);
    if (Global.photoRecordEntity.status == "3") {
      HttpRequest.request(
        "$BASE_URL/photo-record/acceptById",
        params: {"id": id},
        method: "GET",
        token: await StorageUtil.getStringItem("token")
      ).then((value) {
        setState(() {
          Global.photoRecordEntity.status = "2";
          //getStatus(photoRecordEntityDetail);
        });
      });
    }
  }

  Future<Null> delayed(String photoId) async {
    ChatInterface.getPhotoRecord(photoId);
    // 模拟数据的延迟加载
    await Future.delayed(Duration(milliseconds: 300), () {
      print("------chat_id--------------" + Global.photoRecordEntity.id);
      acceptPhotoRecord(Global.photoRecordEntity.id);
      Global.photoRecordEntity.status = "4";
      Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => RecordDetail(photoRecordEntity: Global.photoRecordEntity,),
                  ))
          .then((value) {
        build(context);
      });
    });

  }
}
